<?php
namespace app\lib\exception;

use Exception;  //这里不能写成think\Exception
use think\exception\Handle;
use think\Request;
use think\Log;

class ExceptionHandler extends Handle{
    private $code;
    private $msg;
    private $errorCode;
    //需要返回客户端当前请求的URL路径

    public function render(Exception $e){
        if($e instanceof BaseException){
            //如果是自定义的异常
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        }else{
             // 如果是服务器未处理的异常，将http状态码设置为500，并记录日志
             if(config('app_debug')){  //可随时开启debug模式
                // 调试状态下需要显示TP默认的异常页面，因为TP的默认页面
                // 很容易看出问题
                return parent::render($e);
            }else{
                $this->code = 500;
                $this->msg = '服务器内部错误';
                $this->errorCode = 999;
                $this->recordErrorLog($e);
            }
        };
        $request = Request::instance();

        $result = [
            'msg' => $this->msg,
            'error_code' => $this->errorCode,
            'request_url ' => $request->url()
        ];
        return json($result, $this->code);
    }

    //tp自带的记录日志
    private function recordErrorLog(Exception $e){
        //日志初始化设置
        Log::init([
            'type' => 'File',
            'path' => LOG_PATH,
            'level' => ['error']
        ]);
        //第二个参数是日志级别
        Log::record($e->getMessage(), 'error');
    }
}
?>